package com.example.moneygrosService.handlers;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

import com.example.moneygrosService.MainActivityService.DB_TOKEN;
import com.example.moneygrosService.Request;
import com.example.moneygrosService.User;
import com.example.moneygrosService.database.MoneyContract;
import com.example.moneygrosService.database.MoneyContract.Users;
import com.example.moneygrosService.database.MoneyContract.UsersColumns;
import com.example.moneygrosService.handlers.ResultListener.ResultType;

public class ModifyBalanceHandler extends AsyncQueryHandler {
	private static final String TAG = "ModifyBalanceHandler";
	
	private ContentResolver mCr;
	private Request mRequest;
	private boolean mResult;
	
	private boolean mResultOK;
	
	private ResultListener mListener;

	private boolean mBalanceDone;
	
	public ModifyBalanceHandler(ContentResolver cr) {
		super(cr);
		// TODO Auto-generated constructor stub
		mCr= cr;
	}
	
	public void modifyBalance(Request request){
		mRequest =request;
		CheckAndModifyBalanceHandler checkAndModifyBalanceHandler = new CheckAndModifyBalanceHandler(mCr);
        checkAndModifyBalanceHandler.checkAndModify();
	}


	protected void balanceModified(boolean balanceDone){
		mResultOK = true;
		mResult = balanceDone;
		mBalanceDone = balanceDone;

		if(mListener!=null)
			mListener.onResult(balanceDone, ResultType.USER_INSERTED, null);
	}
	
	public class CheckAndModifyBalanceHandler extends AsyncQueryHandler {
		private static final String TAG = "CheckAndModifyBalanceHandler";
	
		public CheckAndModifyBalanceHandler(ContentResolver cr) {
			super(cr);
		}
		
		public void checkAndModify(){
    		String selection = BaseColumns._ID +"=?";
    		String selectionArgs[] = {String.valueOf(mRequest.getRequest_ID_row())};
    		String[] projection = {BaseColumns._ID, MoneyContract.UsersColumns.USER_ID, MoneyContract.UsersColumns.BALANCE,UsersColumns.BIDIRECTIONAL};
    		startQuery(DB_TOKEN.CHECK_USER_FOR_BALANCE_UPDATE, 
    				(Object)mRequest, 
    				Users.CONTENT_URI, 
    				projection, 
    				selection,
    				selectionArgs,
    				null);
		}

		private void updateBalance(String user_id, double balance) {

			ContentValues values = new ContentValues();
			values.put(MoneyContract.UsersColumns.BALANCE, balance);
			String selection = MoneyContract.UsersColumns.USER_ID+"=?";
			String[] selectionArgs= {user_id};
			startUpdate(DB_TOKEN.UPDATE_BALANCE, null, Users.CONTENT_URI, values, selection, selectionArgs);
		}

		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#onUpdateComplete(int, java.lang.Object, int)
		 */
		@Override
		protected void onUpdateComplete(int token, Object cookie, int result) {
			switch(token){
			case DB_TOKEN.UPDATE_BALANCE:
				
				balanceModified(true);
				break;
			}
		}

		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			// TODO Auto-generated method stub
    		switch(token){

    		case DB_TOKEN.CHECK_USER_FOR_BALANCE_UPDATE:
    			Log.v(TAG, "CHECK_USER_FOR_BALANCE_UPDATE");
    			if(cursor != null){
    				if(cursor.getCount() != 0){
    					cursor.moveToFirst();
    					Request request = (Request)cookie;
    					
    					request.setUser_id(cursor.getString(cursor.getColumnIndex(UsersColumns.USER_ID)));
    					request.setFormer_balance(cursor.getFloat(cursor.getColumnIndex(UsersColumns.BALANCE)));
    					request.setRespondant_user(cursor.getInt(cursor.getColumnIndex(UsersColumns.BIDIRECTIONAL))!=0);
    					
    					request.setNew_balance(request.getOffset() + request.getFormer_balance());
    					
    					cursor.close();
    	    			Log.v(TAG, "updating balance, new balance="+ request.getNew_balance());
    	    			if(request.isRespondant_user()){
    	    				// faire un requete communication
    	    				// ajouter dans la table des requetes 
//    	    				sendRequest(request);
//    	    				sendSMS("5554", request.getUser_id()+ request.getNew_balance());
//    	    				sendSMS("0633287589", request.getUser_id()+ request.getNew_balance());
    	    			} else {
    	    				updateBalance(request.getUser_id(), request.getNew_balance());
    	    			}
    	    			
    	    			// faire requete de Pending ou Log
    				}
    			}
    				
        		break;
    		}
		}

		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#startQuery(int, java.lang.Object, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
		 */
		@Override
		public void startQuery(int token, Object cookie, Uri uri,
				String[] projection, String selection, String[] selectionArgs,
				String orderBy) {
			// TODO Auto-generated method stub
			super.startQuery(token, cookie, uri, projection, selection, selectionArgs,
					orderBy);
		}
		
	}

	public void addResultListener(ResultListener obj) {
		// TODO Auto-generated method stub
		mListener = obj;		
	}

}
